<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="名称">
                <a-input v-model="queryParam.name" placeholder="" />
              </a-form-item>
            </a-col>
            <!-- <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="调用次数">
                  <a-input-number v-model="queryParam.callNo" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="更新日期">
                  <a-date-picker v-model="queryParam.date" style="width: 100%" placeholder="请输入更新日期" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="使用状态">
                  <a-select v-model="queryParam.useStatus" placeholder="请选择" default-value="0">
                    <a-select-option value="0">全部</a-select-option>
                    <a-select-option value="1">关闭</a-select-option>
                    <a-select-option value="2">运行中</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="使用状态">
                  <a-select placeholder="请选择" default-value="0">
                    <a-select-option value="0">全部</a-select-option>
                    <a-select-option value="1">关闭</a-select-option>
                    <a-select-option value="2">运行中</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template> -->
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:role_add>新建</a-button>
      </div>

      <s-table ref="table" size="default" rowKey="id" :columns="columns" :data="loadData" showPagination="auto" :scroll="{ x: 'auto' }">
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" v-action:role_update >编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)" v-action:role_update >删除</a>
            <a-divider type="vertical" />
            <a @click="handleRole(record)"  v-action:role_update >权限设置</a>
          </template>
        </span>
        <span slot="remark" slot-scope="text">
          <div class="remark-wrap">{{text}}</div>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <role-form
        ref="roleModal"
        :visible="role.visible"
        :loading="role.confirmLoading"
        :model="role.mdl"
        :allRole="allRole"
        :role="role.role"
        @cancel="handleRoleCancel"
        @ok="handleRoleOk"
      />
      <!-- <step-by-step-modal ref="modal" @ok="handleOk" /> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { roleList, roleAdd, roleUpdate, permissionGetAll, permissionUpdate, permission } from '@/api/role'
import { Modal } from 'ant-design-vue'
// import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import RoleForm from './modules/RoleForm'
const columns = [
  // id、名称、备注、添加人、添加时间、最后编辑人、最后编辑时间
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '名称',
    dataIndex: 'name',
    width:'150px',
    key: 'name',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    scopedSlots: { customRender: 'remark' },
  },
  {
    title: '添加人',
    dataIndex: 'addUserName',
    key: 'addUserName',
    width:'100px',
    customRender: (text) => text || '--',
  },
  {
    title: '添加时间',
    dataIndex: 'addTime',
    key: 'addTime',
    width:'180px',
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑人',
    dataIndex: 'lastUpdateUserName',
    width:'120px',
    key: 'lastUpdateUserName',
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑时间',
    dataIndex: 'lastUpdateTime',
    key: 'lastUpdateTime',
    width:'180px',
    customRender: (text) => text || '--',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    scopedSlots: { customRender: 'action' },
  },
]

const statusMap = {
  0: {
    status: 'default',
    text: '关闭',
  },
  1: {
    status: 'processing',
    text: '运行中',
  },
  2: {
    status: 'success',
    text: '已上线',
  },
  3: {
    status: 'error',
    text: '异常',
  },
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    RoleForm,
  },
  data() {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      role: {
        visible: false,
        mdl: null,
        confirmLoading: false,
        role:[]
      },
      allRole: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParam: {},
      data: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return roleList(requestParameters).then((res) => {
          let result = {
            data: res.data.data,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    },
  },
  created() {
    this.getAllRole()
    // getRoleList({ t: new Date() })
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
  },
  methods: {
    
    getAllRole() {
      PermissionGetAll().then((res) => {
        this.allRole = res.data
      })
    },
    getList() {
      let data = Object.assign({}, this.parameter, this.queryParam)
      roleList(data)
        .then((res) => {
          this.data = res.data.data
        })
        .catch((err) => {})
    },
    // 权限设置
    handleRole(record) {
      permission({roleId: record.id}).then(res=>{
        this.role.visible = true
        this.role.mdl = { ...record }
        this.role.role = res.data
      })
      
    },
    handleRoleCancel() {
      this.role.visible = false
      // const role = this.$refs.roleModal
    },
    handleRoleOk() {
      const modal = this.$refs.roleModal
      this.role.confirmLoading = true
      let data = {
        roleId:modal.model.id,
        rolePermissionList:modal.getRolePermissionList(),
      }
      permissionUpdate(data).then((res) => {
            this.role.visible = false
            this.role.confirmLoading = false
            // 重置表单数据
            // form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.success('编辑成功!')
          })
          .catch(err=>{
            this.role.confirmLoading = false
            this.$message.error('编辑失败!')
          })
    },
    // 角色添加
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.id > 0) {
            roleUpdate(values).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('修改成功!')
            })
          }else{
            delete values.id
            roleAdd(values).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('新增成功!')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
    handleDel(a_record) {
      let self = this
      const modal = Modal.confirm({
        title: '角色删除',
        content: `是否删除角色:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDeleteRole(a_record.id, modal),
        onCancel: () => {},
      })
    },
    handleDeleteRole(a_id, a_modal) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id, status: -1 }
        roleUpdate(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('删除成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
  },
}
</script>

 